<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="猪只耳号" prop="pigCode">
        <el-input
          v-model="queryParams.pigCode"
          placeholder="请输入猪只耳号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所在栏舍" prop="phouseType">
        <el-select
          v-model="queryParams.phouseType"
          placeholder="栏舍类型"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.hmy_park_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="进场时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['hmy:pig:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['hmy:pig:update']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['hmy:pig:del']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:user:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:user:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pigList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="猪只耳号" prop="pigCode" width="100" align="center"/>
      <el-table-column label="猪只品种" align="center" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.hmy_pig_breed" :value="scope.row.pigBreed"/>
        </template>
      </el-table-column>
      <el-table-column label="猪只种类" align="center" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.hmy_pig_type" :value="scope.row.pigType"/>
        </template>
      </el-table-column>

      <el-table-column label="出生日期" align="center" prop="pigBirthday" width="180">
        <template slot-scope="scope">
          {{scope.row.pigBirthday.slice(0, 10)}}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="creationDate" width="180">
        <template slot-scope="scope">
          {{scope.row.pigBirthday.slice(0, 10)}}
        </template>
      </el-table-column>
      <el-table-column label="二维码" align="center" width="100" >
        <template slot-scope="scope" style="width: 5px">
          <el-image
            :src="scope.row.codeUrl"
            fit="cover"
            placeholder="https://your-cloud-url/placeholder.jpg"
            :preview-src-list="[scope.row.codeUrl]"
            @click="onPreview"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.materiaPigId !== 0">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-detail"
            @click="handleDetail(scope.row)"
            v-hasPermi="['hmy:pig:query']"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['hmy:pig:update']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['hmy:pig:del']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />



    <!-- 详情页面-->
    <el-dialog :title="title" :visible.sync="detail" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="猪只耳号" prop="pigCode">
              <el-input v-model="form.pigCode" placeholder="请输入猪只耳号"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属批次" prop="pigBatch">
              <el-input v-model="form.pigBatch"placeholder="请输入批次编号"  />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="猪只品种" prop="pigBreed">
              <el-select
                v-model="form.pigBreed"
                placeholder="请选择猪只类型"
                style="width: 280px"
              >
                <el-option
                  v-for="dict in dict.type.hmy_pig_breed"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="猪只类型" prop="pigType">
              <el-select
                v-model="form.pigType"
                placeholder="请选择猪只类型"
                style="width: 280px"
              >
                <el-option
                  v-for="dict in dict.type.hmy_pig_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生时间" prop="pigBirthday">
              <el-date-picker
                v-model="form.pigBirthday"
                placeholder="请选择出生时间"
                style="width: 280px"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="栏舍类型" prop="phouseType">
              <el-select
                v-model="form.phouseType"
                placeholder="请选择栏舍类型"
                style="width: 280px"
              >
                <el-option
                  v-for="dict in dict.type.hmy_park_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="栏舍编号" prop="phouseCode">
              <el-input v-model="form.phouseCode" placeholder="请输入栏舍编号"/>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>

          <el-col :span="12">
            <el-form-item label="猪只状态" prop="pigStatus">
              <el-select
                v-model="form.pigStatus"
                placeholder="请选择猪只状态"
                style="width: 280px"
              >
                <el-option
                  v-for="dict in dict.type.hmy_pig_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>

        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
<!--      <div slot="footer" class="dialog-footer">-->
<!--&lt;!&ndash;        <el-button type="primary" @click="submitForm">确 定</el-button>&ndash;&gt;-->
<!--        <el-button @click="cancel">取 消</el-button>-->
<!--      </div>-->
    </el-dialog>

    <!-- 添加或修改-->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="猪只耳号" prop="pigCode">
              <el-input v-model="form.pigCode" placeholder="请输入猪只耳号"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属批次" prop="pigBatch">
              <el-input v-model="form.pigBatch"placeholder="请输入批次编号"  />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="猪只品种" prop="pigBreed">
              <el-select
                v-model="form.pigBreed"
                placeholder="请选择猪只类型"
                style="width: 280px"
              >
                <el-option
                  v-for="dict in dict.type.hmy_pig_breed"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="猪只类型" prop="pigType">
              <el-select
                v-model="form.pigType"
                placeholder="请选择猪只类型"
                style="width: 280px"
              >
                <el-option
                  v-for="dict in dict.type.hmy_pig_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="出生时间" prop="pigBirthday">
              <el-date-picker
                v-model="form.pigBirthday"
                placeholder="请选择出生时间"
                style="width: 280px"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="栏舍类型" prop="phouseType">
              <el-select
                v-model="form.phouseType"
                placeholder="请选择栏舍类型"
                style="width: 280px"
              >
                <el-option
                  v-for="dict in dict.type.hmy_park_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="栏舍编号" prop="phouseCode">
              <el-input v-model="form.phouseCode" placeholder="请输入栏舍编号"/>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>

          <el-col :span="12">
            <el-form-item label="猪只状态" prop="pigStatus">
              <el-select
                v-model="form.pigStatus"
                placeholder="请选择猪只状态"
                style="width: 280px"
              >
                <el-option
                  v-for="dict in dict.type.hmy_pig_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" v-loading="uploadLoading" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>


import { listPig,getPig, delPig, addPig, updatePig,getPigByPigCode} from "@/api/hmy/pig";
import { getToken } from "@/utils/auth";
import {dowlan} from "../../../api/hmy/pig";
import {download} from "../../../utils/request";

export default {
  name: "Pig",
  dicts: ['hmy_pig_breed', 'hmy_pig_type', 'hmy_park_type', 'hmy_pig_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      //弹出层遮罩
      uploadLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 进货表格数据
      pigList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      detail: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: undefined,
        pigCode: undefined,
        pigBreed: undefined,
        pigType: undefined,
        pigBatch: undefined,
        phouseType: undefined,
        phouseCode: undefined,
        pigStatus: undefined,
        pigBirthday: undefined,
        dateStart: undefined,
        dateEnd: undefined

      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/hmy/pig/upload"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        pigCode: [
          {required: true, message: "耳号不能为空", trigger: "blur"},
          {
            validator: async (rule, value, callback) => {
              var pigCode = this.form.pigCode;
              if (pigCode != undefined) {
                if (pigCode = this.pigCode) {
                  await getPigByPigCode(pigCode).then(response => {
                    if (response.data != null) {
                      callback(new Error("已存在"))
                    }
                  })
                }
              }
            }, trigger: 'blur'
          }
        ],

        pigBreed: [
          {required: true, message: "猪只品种不可为空", trigger: "blur"}
        ],
        pigType: [
          {required: true, message: "猪只类型为空", trigger: "blur"}
        ],
        pigBatch: [
          {required: true, message: "猪只批次不能为空", trigger: "blur"}
        ],
        phouseType: [
          {required: true, message: "所在栏舍类型不能为空", trigger: "blur"}
        ],
        phouseCode: [
          {required: true, message: "栏舍编码不能为空", trigger: "blur"}
        ],
        pigStatus: [
          {required: true, message: "猪只状态不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    onPreview() {
      //调用image组件中的大图浏览图片方法
      this.$refs.preview.clickHandler();
    },
    /** 查询猪只档案列表 */
    getList() {
      this.loading = true;
      this.queryParams.dateStart = this.dateRange[0];
      this.queryParams.dateEnd = this.dateRange[1];
      listPig(this.queryParams).then(response => {
          this.pigList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        pigCode: undefined,
        pigBreed: undefined,
        pigType: undefined,
        pigBatch: undefined,
        phouseType: undefined,
        phouseCode: undefined,
        pigStatus: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      //this.resetForm("queryForm");
      this.queryParams = {};
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.pigId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    //添加按钮
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加猪只档案信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const pigId = row.pigId || this.ids
      getPig(pigId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改猪只档案信息";
      });
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.pigId != undefined) {

            updatePig(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPig(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const pigIds = row.pigId || this.ids;
      this.$modal.confirm('是否确认删除猪只档案编号为"' + pigIds + '"的数据项？').then(function () {
        return delPig(pigIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /**  详情按钮操作 */
    handleDetail(row) {
      this.reset();
      const pigId = row.pigId || this.ids
      getPig(pigId).then(response => {
        this.form = response.data;
        this.detail = true;
        this.title = "查看猪只档案信息";
      });

    },

    // 前端发送请求到后端下载文件
    handleExport() {
      dowlan().then(response => {
        // 下载成功后弹出消息
        this.$message.success("文件已下载到 C:\\Users\\Administrator\\Downloads");
      }).catch(error => {
        // 下载失败时处理错误
        console.error('下载文件失败：', error);
        // 弹出错误消息
        this.$message.error("下载失败，请联系管理员！");
      });
    },


    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.uploadLoading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.uploadLoading = true;
      this.$refs.upload.submit();
    }

  }
}

</script>
